package app

import (
	"context"
	"fmt"

	"charging_pile/common/globalkey"
	"charging_pile/common/tool"
	"charging_pile/common/xerr"
	"charging_pile/user/internal/svc"
	"charging_pile/user/internal/types"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetValidateCodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetValidateCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetValidateCodeLogic {
	return &GetValidateCodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetValidateCodeLogic) GetValidateCode(req *types.GetValidateReq) error {
	code := tool.Krand(4, tool.KC_RAND_KIND_NUM)
	key := fmt.Sprintf(globalkey.PhoneCodeAuth, req.Appid, req.Phone)
	err := l.svcCtx.RedisObj.SetexCtx(l.ctx, key, code, 300)
	if err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.CACHE_ERR), "存储验证码失败:%s", code)
	}

	go func() {
		logx.Infof("sms appid:%s phone:%s code:%s", req.Appid, req.Phone, code)
		err := l.svcCtx.SmsClient.SendSms(req.Phone, "1796622", code)
		if err != nil {
			logx.Errorf("sms phone:%s code:%s,err:%+v", req.Phone, code, err)
		}
	}()

	return nil
}
